<?php

namespace control;

/*
*明细账类
*/


class accountDetailsClass extends adIndexClass
{
    private const page        = 'accountDetails'; # 权限
    private const title       = '明细账';
    public const  styleOption = ['金额式', '数量金额式'];
    public static bool $isFormat = false;//是否格式化数字

    public static function getDepartmentAll($data = []): string
    {
        $dateWhere = static::rGet(self::$stid .self::$coid. 'SearchMonth') ?: date('Y-m',strtotime(self::getMinDate())) . ' ~ ' . date('Y-m',strtotime(self::getMaxDate()));
        // 条件
        $data['where'] = $data['where'] ?? "pid='0'";
        $where         = self::timeComparison($dateWhere, 'month', field: "b.recordDate");
        // 点击事件
        $data['click'] = $data['click'] ?? "replaceDetail(this,'" . self::page . "')";

        //限制在凭证中的科目和期初中的科目
        $subjectIds = [];
        $all        = find(['table' => 'voucher_detail as a join voucher as b on a.orderId = b.id', "field" => "a.*", 'where' => "a.coid = '" . self::$coid . "' " . $where]);
        foreach ($all['array'] as $array) {
            $subjectIds = array_merge($subjectIds, multiColumnAccountClass::loopSubjectPre($array['subjectId']));
        }
        $all        = find(['table' => 'subject', 'where' => "coid = '" . self::$coid . "' and (initMoney !=0 or borrowMoney !=0 or loanMoney !=0)"]);
        $subjectIds = array_merge($subjectIds, array_column($all['array'], 'subjectId'));
        $subjectIds = array_unique($subjectIds);
        // 结果
        $result = find(array('table' => 'subject', 'where' => "coid = '" . self::$coid . "' and id in ('" . implode("','", $subjectIds) . "') order by list asc,level asc,selfIndex asc"));
        $style  = ($data['where'] == "pid='0'") ? '' : ' class="child-node"';
        $temp   = "<ul {$style} {$data['where']}>";
        $ico = "<span class='textcontent_ico'></span>";
        static::rSet(self::$stid . self::page . 'subjectId', $result['array'][0]['id'] ?? '');
        foreach ($result['array'] as $index => $array) {
            $empty = '';
            if ($array['level'] > 1) {
                for ($i = 1; $i < $array['level']; $i++) {
                    $empty .= "&emsp;";
                }
            }
            /*$ico = '';
            if (static::total(array('table' => 'subject', 'where' => "coid = '" . self::$coid . "' and pid = '$array[id]'")) > 0) {
                $ico = "<span class='textcontent_ico'></span>";
            }*/
            $temp .= "<li class='arrow-no-li'  data-id='{$array['id']}' title='{$array['code']}&nbsp;{$array['name']}' onclick=\"{$data['click']}\">
                        <span class='textcontent'>$empty $ico {$array['code']}&nbsp;{$array['name']}</span>
                    </li>";
        }
        $temp .= '</ul>';
        return $temp;
    }

    /**
     * 异步加载
     *
     */
    public function homeRightJson(): bool|string
    {
        $json['html'] = $this->homeRight();
        return json_encode($json, 320);
    }

    public function homeRightJsonSearch(): bool|string
    {
        return $this->homeSearch();
    }

    /**
     * 左侧搜索框
     *
     * @return string
     */
    public function getContainerLeftJson(): string
    {
        static::rSet(self::$stid .self::$coid. 'SearchMonth', $this->post('createTime'));
        $option['click'] = "replaceContent(this, 'accountDetails')";
        $json['html']    = self::getDepartmentAll($option);
        return json_encode($json, 320);
    }


    /*列表页-查询条件*/
    public function home()
    {
        $id = $this->get('id');
        //返回
        $rightHtml       = $this->homeRight();
        $option['click'] = "replaceContent(this, 'accountDetails')";
        $all             = self::getDepartmentAll($option);
        $html = componentClass::leftNav([
            'title'=>'搜索科目',
            'all'=>$all,
            'rightHtml'=>$rightHtml,
        ]);
        $html            .= <<<EOT
<style>
#container-detail{flex: 1;height: calc(100% - 170px);display: block;overflow: auto;min-height: unset;}
#homeRightJsonSearchHtml{padding: 0 15px;overflow: auto}
#homeRightJsonSearchHtml .tableMany{width: 100%}
</style>
<script>
function cancelPage(id){
    let obj =  $("[data-id='"+id+"']");
    if (id && obj.length >0){
        replaceContent(obj,'accountDetails');
    }
}
 $(function (){
     cancelPage('$id')
 })
</script>
EOT;
        //返回
        return $this->homeFun($html . $this->js());
    }

    public function js(): string
    {
        return <<<eof
<script>
   function changeTableStyle(e){
       let val = e.value;
       $.post(root+'control/adIndex.html?cla=accountDetails&fun=changeTableStyle',{style:val},function(res) {
            if (res.warn==2){
                location.reload();
            }else{
                msg(res.warn,'error')
            }
       },'json')
   }
</script>
eof;
    }

    /**
     * 修改列表样式
     * @return bool|string
     */
    public function changeTableStyle(): bool|string
    {
        $style = $this->post('style');

        if (!in_array($style, self::styleOption)) {
            $json['warn'] = '请选择列表样式';
        } else {
            $json['warn'] = 2;
            static::rSet(self::$stid . self::page . 'tableStyle', $style);
        }
        return json_encode($json, 320);
    }

    /**
     * 在凭证中获取最大的月份
     */
    public static function getMaxDate(): string
    {
        $voucher = query('voucher',"coid = '".self::$coid."' order by recordDate desc");
        if ($voucher['id']){
            return date('Y-m',strtotime($voucher['recordDate'])).'-'.date('t',strtotime($voucher['recordDate']));
        }
        return self::getMinDate();
    }

    /**
     * 获取账套启用月份
     */
    public static function getMinDate(): string
    {
        $company = query('company',"coid = '".self::$coid."'");
        return $company['startDate'].'-01';
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        $typeId = $this->post('objId') ?? null;
        $maxDate = static::getMaxDate();
        $minDate = static::getMinDate();
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "会计期间" => text(array(
                        "name" => "createTime",
                        'value' => static::rGet(self::$stid .self::$coid. 'SearchMonth') ?: date('Y-m',strtotime($maxDate)) . ' ~ ' . date('Y-m',strtotime($maxDate)),
                        'laydate' => ['type' => 'month','range'=>'~','min'=>"'{$minDate}'",'max'=>"'{$maxDate}'"]
                        )).
                        hidden(array('name' => 'subjectId', 'value' => $typeId)),
                ]
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    public function homeRight()
    {
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        if ($this->power(self::page, "export")) {
            $button .= "  <a href='" . root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=exportData'><span class='spanButton'>导出</span></a>\n";
        }
        $button .= "<select class='select'  onchange='changeTableStyle(this)'>" . option(array('value' => static::rGet(self::$stid . self::page . 'tableStyle'), 'option' => self::styleOption)) . "</select>";
        //返回
        return $this->search($html, layout: 'pop', toolButton: $button);
    }

    public function homeSearch(): bool|string
    {
        static::rSet(self::$stid .self::$coid. 'SearchMonth', $this->post('createTime'));;
        $style = static::rGet(self::$stid . self::page . 'tableStyle');
        if (empty($style)) {
            static::rSet(self::$stid . self::page . 'tableStyle', self::styleOption[0]);
            $style = self::styleOption[0];
        }
        static::rSet(self::$stid . self::page . 'tableStyle', $style);
        if ($style == '金额式') {
            $json['html'] = $this->onlyMoneySearch();//金额式
        } else {
            $json['html'] = $this->moneyAndNumSearch();//数量金额式
        }
        $json['html'].=<<<eof
<script>
function searchFormSub(cla, fun) {
    $.post(root+'control/adIndex.html?cla=accountDetails&fun=getContainerLeftJson',{createTime:$("[name='createTime']").val()},function(res) {
      $("#container-left .classify-area").empty().append(res.html);
      searchForm(cla, fun, 1);
    },'json')
    return false;
}
</script>
eof;

        return json_encode($json, 320);
    }

    /**
     * 查询条件
     * @param $subjectId
     * @return string
     */
    public function sqlWhere($subjectId): string
    {
        $like         = array();
        $subjectIdArr = multiColumnAccountClass::loopSubjectAllChildren($subjectId);
        //全等查询数组
        $equal = array(
            "a.coid"       => self::$coid,
            "a.isTemplate" => '否',
        );
        $and   = " and b.subjectId in ('" . implode("','", $subjectIdArr) . "')" . voucherClass::joinWhere();
        if ($this->post('createTime')) {
            $and .= self::timeComparison($this->post('createTime'), 'month', field: "a.recordDate");
        }
        //获取查询结果
        return search(array("like" => $like, "=" => $equal)) . $and;
    }

    /**
     * 数量金额式
     * @return string
     */
    public function moneyAndNumSearch(): string
    {
        //数量金额式
        $subjectId = static::rGet(self::$stid . self::page . 'subjectId');
        if (empty($this->post('subjectId')) && $subjectId) {
            $subject   = query('subject', "id = '$subjectId'");
            $subjectId = $subject['id'];
        } else {
            $subjectId = $this->post('subjectId');
        }

        $arr        = $this->post('createTime') ? explode(' ~ ', $this->post('createTime')) : [date('Y-m',strtotime(self::getMinDate())), date('Y-m',strtotime(self::getMaxDate()))];
        $startMonth = trim($arr[0]);
        $initDate   = $startMonth . '-01';
        //获取查询结果
        $where = $this->sqlWhere($subjectId);
        $page  = $this->page(array("table" => "voucher as a join voucher_detail as b on a.id = b.orderId", 'field' => "b.*,a.voucherNo,a.recordDate,a.voucherWordId", "where" => $where, "order" => "a.recordDate asc,a.voucherNo,b.list"));

        static::rSet(self::$stid . self::page . 'sql', $page['fullSql']);
        static::rSet(self::$stid . self::page . 'subjectId', $subjectId);
        static::rSet(self::$stid . self::page . 'time', $this->post('createTime'));

        $url            = root . "control/adIndex.html?cla=voucherEdit&fun=home";
        $subject        = query('subject', "id = '$subjectId'");
        self::$isFormat = true;//设置需要格式金额
        $tr             = '';
        $multi          = new multiColumnAccountClass();
        if ($subject['id']) {
            $multi->loopSubjectIds($subject['id'],$subjectIdCollection);
            $result = $this->initMoneyDetail($subjectIdCollection, $startMonth);
//            $result = $this->initMoney($subject['id'], $startMonth);
            //期初余额
            $tr = <<<eof
<tr>
 <td>{$subject['code']}&nbsp;{$subject['name']}</td>
      <td>$initDate</td>
      <td></td>
      <td>期初余额</td>
      <td>{$result['jieInitNum']}</td><td>{$result['jiePrice']}</td><td>{$result['jieMoney']}</td>
      <td>{$result['daiInitNum']}</td><td>{$result['daiPrice']}</td><td>{$result['daiMoney']}</td>
      <td>{$result['balanceNum']}</td>
      <td>{$result['balancePrice']}</td>
      <td>{$result['jieBalance']}</td>
      <td>{$result['daiBalance']}</td>
</tr>
eof;
        }

        foreach ($page['array'] as $index => $array) {
            $jieHtml             = "<td></td><td></td><td></td>";
            $daiHtml             = "<td></td><td></td><td></td>";
            $voucher_word        = query('voucher_word', "id = '$array[voucherWordId]'");
            $array['money']      = number_format(self::centToYuan($array['money']), 2);
            $array['voucherNum'] = voucherClass::zeroToEmpty(voucherEditClass::formatZero($array['voucherNum']));
            if ($array['direction'] == '借') {
                $subjectAttr                 = json_decode($array['subjectAttr'], true);
                $subjectAttr['voucherPrice'] = $subjectAttr['voucherPrice'] ? floatval($subjectAttr['voucherPrice']) : '';
                $jieHtml                     = "<td>{$array['voucherNum']}</td><td>{$subjectAttr['voucherPrice']}</td><td>{$array['money']}</td>";
            } else {
                $subjectAttr                 = json_decode($array['subjectAttr'], true);
                $subjectAttr['voucherPrice'] = $subjectAttr['voucherPrice'] ? floatval($subjectAttr['voucherPrice']) : '';
                $daiHtml                     = "<td>{$array['voucherNum']}</td><td>{$subjectAttr['voucherPrice']}</td><td>{$array['money']}</td>";
            }
            $balance  = $this->balance($array['recordDate'], $array['subjectId'], $array['voucherNo']);
            $pinzheng = $voucher_word['word'] ? "<span class='del-row-button' onclick=\"newIframe('录凭证','{$url}&id={$array['orderId']}')\">{$voucher_word['word']}-{$array['voucherNo']}</span>" : '';
            $tr       .= <<<eof
                 <tr>
                 <td>{$array['subjectCode']}&nbsp;{$array['subjectName']}</td><td>{$array['recordDate']}</td><td>{$pinzheng}</td><td>{$array['summary']}</td>
                  {$jieHtml}{$daiHtml}<td>{$balance['balanceNum']}</td><td>{$balance['balancePrice']}</td><td>{$balance['jieBalance']}</td><td>{$balance['daiBalance']}</td>
                 </tr>
eof;

            if ((isset($page['array'][$index + 1]['subjectId']) && (date('Y-m', strtotime($page['array'][$index + 1]['recordDate'])) != date('Y-m', strtotime($array['recordDate'])))) ||
                !isset($page['array'][$index + 1]['subjectId'])
            ) {
                $endMonthDate = date('Y-m', strtotime($array['recordDate']));
                $result       = $this->monthBalanceDetail(date('Y-m', strtotime($array['recordDate'])), $subjectIdCollection??[]);
                $balance      = $this->balanceDetail($array['recordDate'],  $subjectIdCollection??[], '累计');
                $totalBalance = $this->monthBalanceDetail(date('Y-m', strtotime($array['recordDate'])), $subjectIdCollection??[], 'year');
                $tr           .= <<<eof
                     <tr>
                      <td>{$subject['code']}&nbsp;{$subject['name']}</td>
                        <td>{$endMonthDate}</td>
                        <td></td>
                       
                        <td class="l-b-color">本期合计</td>
                        <td>{$result['jieNum']}</td>
                        <td>{$result['jiePrice']}</td>
                        <td>{$result['jieMoney']}</td>
                         <td>{$result['daiNum']}</td>
                        <td>{$result['daiPrice']}</td>
                        <td>{$result['daiMoney']}</td>
                         <td>{$balance['balanceNum']}</td>
                        <td>{$balance['balancePrice']}</td>
                        <td>{$balance['jieBalance']}</td>
                        <td>{$balance['daiBalance']}</td>
                     </tr>
                    <tr>
                     <td>{$subject['code']}&nbsp;{$subject['name']}</td>
                        <td><span class="divider">$endMonthDate</span></td>
                        <td></td>
                       
                        <td class="l-orange-color">本年累计</td>
                        <td>{$totalBalance['jieNum']}</td>
                        <td>{$totalBalance['jiePrice']}</td>
                        <td>{$totalBalance['jieMoney']}</td>
                       <td>{$totalBalance['daiNum']}</td>
                        <td>{$totalBalance['daiPrice']}</td>
                        <td>{$totalBalance['daiMoney']}</td>
                        <td>{$balance['balanceNum']}</td>
                        <td>{$balance['balancePrice']}</td>
                        <td>{$balance['jieBalance']}</td>
                        <td>{$balance['daiBalance']}</td>
                     </tr>
<tr><td colspan="14" style="background-color: #f2f2f2"></td></tr>
eof;
            }

        }

        $hide = '';
        if (empty($subject['id'])) {
            $hide = "hide";
        }
        $subject['numAccountText'] = $subject['numAccountText'] ?: '-';

        // 月份选择器
        $monthSelector = componentClass::monthSelector(implode('~',$arr));
        $html                      = <<<eof
                <div class="finance-subject-head $hide">科目：{$subject['code']}&nbsp;{$subject['name']}&emsp;&emsp;单位：{$subject['numAccountText']} {$monthSelector['button']}</div>
                <table class="tableMany">
                    <thead>
                        <tr><td rowspan="2" style="vertical-align:middle">科目</td><td rowspan="2" style="vertical-align:middle">日期</td><td rowspan="2" style="vertical-align:middle">凭证字</td><td rowspan="2" style="vertical-align:middle">摘要</td><td colspan="3" class="center">借方</td><td colspan="3" class="center">贷方</td><td colspan="4" class="center">余额</td></tr>
                        <tr><td>数量</td><td>单价</td><td>金额</td><td>数量</td><td>单价</td><td>金额</td><td>数量</td><td>单价</td><td>借方金额</td><td>贷方金额</td></tr>
                    </thead>
                    <tbody>
                       $tr
                    </tbody>
                </table>
eof;
        //返回
        return $page['hint'] .
            "<div class='acct-main-container'>
                <form name='listForm'>" .
                    $html .
                "</form>" .
                $monthSelector['html'].
            "</div>" .
            $page['button'] .
            clear;
    }


    /**
     * 金额式
     */
    public function onlyMoneySearch(): string
    {
        $subjectId = static::rGet(self::$stid . self::page . 'subjectId');
        if (empty($this->post('subjectId')) && $subjectId) {
            $subject   = query('subject', "id = '$subjectId'");
            $subjectId = $subject['id'];
        } else {
            $subjectId = $this->post('subjectId');
        }
        $multi      = new multiColumnAccountClass();
        $arr        = $this->post('createTime') ? explode(' ~ ', $this->post('createTime')) : [date('Y-m',strtotime(self::getMinDate())), date('Y-m',strtotime(self::getMaxDate()))];
        $startMonth = trim($arr[0]);
        $initDate   = $startMonth . '-01';
        //获取查询结果
        $where = $this->sqlWhere($subjectId);
        $page  = $this->page(array("table" => "voucher as a join voucher_detail as b on a.id = b.orderId", 'field' => "b.*,a.voucherNo,a.recordDate,a.voucherWordId", "where" => $where, "order" => "recordDate asc,a.voucherNo asc,b.list"));
        static::rSet(self::$stid . self::page . 'sql', $page['fullSql']);
        static::rSet(self::$stid . self::page . 'subjectId', $subjectId);
        static::rSet(self::$stid . self::page . 'time', $this->post('createTime'));

        $url            = root . "control/adIndex.html?cla=voucherEdit&fun=home";
        $subject        = query('subject', "id = '$subjectId'");
        self::$isFormat = true;
        $tr             = '';
        if ($subject['id']) {
            $multi->loopSubjectIds($subject['id'], $subjectIds);
            $result = $this->initMoneyDetail($subjectIds, $startMonth);
            $tr     = <<<eof
                    <tr>
                    <td>{$subject['code']}&nbsp;{$subject['name']}</td>
                        <td>$initDate</td>
                        <td></td>
                        <td>期初余额</td>
                        <td>{$result['jieMoney']}</td>
                        <td>{$result['daiMoney']}</td>
                        <td>{$result['jieBalance']}</td>
                        <td>{$result['daiBalance']}</td>
                     </tr>
eof;
        }
        foreach ($page['array'] as $index => $array) {
            $voucher_word   = query('voucher_word', "id = '$array[voucherWordId]'");
            $array['money'] = number_format(self::centToYuan($array['money']), 2);
            $pinzheng       = $voucher_word['word'] ? componentClass::urlTitle($voucher_word['word'] . '-' . $array['voucherNo'], $url . "&id={$array['orderId']}", '录凭证') : '';
            if ($array['direction'] == '借') {
                $jie = $array['money'];
                $dai = '';
            } else {
                $jie = '';
                $dai = $array['money'];
            }
            $result = $this->balance($array['recordDate'], $array['subjectId'], $array['voucherNo']);
            $tr     .= <<<eof
                     <tr>
                       <td>{$array['subjectCode']}&nbsp;{$array['subjectName']}</td>
                        <td>{$array['recordDate']}</td>
                        <td>{$pinzheng}</td>
                        <td>{$array['summary']}</td>
                        <td>$jie</td>
                        <td>$dai</td>
                        <td>{$result['jieBalance']}</td>
                        <td>{$result['daiBalance']}</td>
                     </tr>
eof;
            if ((isset($page['array'][$index + 1]['subjectId']) && (date('Y-m', strtotime($page['array'][$index + 1]['recordDate'])) != date('Y-m', strtotime($array['recordDate'])))) ||
                !isset($page['array'][$index + 1]['subjectId'])
            ) {
                //$balance      = $this->balance($array['recordDate'], $array['subjectId'], '累计');
                //$totalBalance = $this->monthBalance(date('Y-m', strtotime($array['recordDate'])), $subject['id'], 'year');
                $endMonthDate = date('Y-m', strtotime($array['recordDate']));
                $result       = $this->monthBalanceDetail(date('Y-m', strtotime($array['recordDate'])), $subjectIds??[]);
                $balance      = $this->balanceDetail($array['recordDate'],  $subjectIds??[], '累计');
                $totalBalance = $this->monthBalanceDetail(date('Y-m', strtotime($array['recordDate'])), $subjectIds??[], 'year');
                $tr           .= <<<eof
                     <tr>
                     <td>{$subject['code']}&nbsp;{$subject['name']}</td>
                        <td>{$endMonthDate}</td>
                        <td></td>
                        <td class="l-b-color">本月合计</td>
                        <td>{$result['jieMoney']}</td>
                        <td>{$result['daiMoney']}</td>
                        <td>{$balance['jieBalance']}</td>
                        <td>{$balance['daiBalance']}</td>
                     </tr>
                    <tr>
                      <td>{$subject['code']}&nbsp;{$subject['name']}</td>
                        <td><span class="divider">$endMonthDate</span></td>
                        <td></td>
                        <td class="l-orange-color">本年累计</td>
                        <td>{$totalBalance['jieMoney']}</td>
                        <td>{$totalBalance['daiMoney']}</td>
                        <td>{$balance['jieBalance']}</td>
                        <td>{$balance['daiBalance']}</td>
                     </tr>
<tr><td colspan="8" style="background-color: #f2f2f2"></td></tr>
eof;
            }
        }
        $hide      = $subject['id'] ? '' : 'hide';
        $unitTitle = $subject['numAccount'] == '是' ? "单位：{$subject['numAccountText']}" : '';
        // 月份选择器
        $monthSelector = componentClass::monthSelector(implode('~',$arr));
        $html      = <<<eof
<div class="finance-subject-head $hide">科目：{$subject['code']}&nbsp;{$subject['name']}&emsp;&emsp;$unitTitle {$monthSelector['button']}</div>
<table class="tableMany">
    <thead>
        <tr>
            <td>科目</td>
            <td>日期</td>
            <td>凭证字</td>
            <td>摘要</td>
            <td>借方</td>
            <td>贷方</td>
            <td>借方余额</td>
            <td>贷方余额</td>
        </tr>
    </thead>
    <tbody>
       $tr
    </tbody>
</table>
eof;
        //返回
        return $page['hint'] .
            "<div class='acct-main-container'>
                <form name='listForm'>" .
                    $html .
                "</form>" .
                $monthSelector['html'].
            "</div>" .
            $page['button'] .
            clear;
    }

    /**
     * 把返回的数组数字格式化为金额格式，数量消除小数点
     */
    public static function formatArrayNumber($array, $eliminate = [])
    {
        if (is_array($array)) {
            foreach ($array as $index => $value) {
                if (in_array($index, $eliminate)) {
                    continue;
                }
                if (is_numeric($value)) {
                    if (currencyClass::calculateDecimal(floatval($value)) > 100) {
                        $array[$index] = $value != 0 ? floatval($value) : ' ';
                    } else {
                        $array[$index] = $value != 0 ? number_format($value, 2) : ' ';
                    }
                }
            }
        }
        return $array;
    }

    /**
     * 期初余额
     * @param $subjectId
     * @param $startMonth
     * @return array
     */
    public function initMoney($subjectId, $startMonth): array
    {
        $where   = voucherClass::joinWhere();
        $subject = query('subject', "id = '$subjectId'");
        //期初金额
        $initNum          = find(array('table' => 'subject_assist', "where" => "orderId = '$subject[id]'", 'sum' => "initNum"));
        $jieNum           = find(array('table' => 'subject_assist', "where" => "orderId = '$subject[id]'", 'sum' => "jieNum"));
        $daiNum           = find(array('table' => 'subject_assist', "where" => "orderId = '$subject[id]'", 'sum' => "daiNum"));
        $jieInit          = find(array("table" => "voucher as a join voucher_detail as b on a.id = b.orderId", 'field' => "ifnull(sum(b.money),0) as money,ifnull(sum(b.voucherNum),0) as num", "single" => "a.isTemplate = '否' and a.coid = '" . self::$coid . "' and b.subjectId = '$subject[id]' and b.direction = '借' and date_format(a.recordDate,'%Y-%m') < '$startMonth'" . $where));
        $daiInit          = find(array("table" => "voucher as a join voucher_detail as b on a.id = b.orderId", 'field' => "ifnull(sum(b.money),0) as money,ifnull(sum(b.voucherNum),0) as num", "single" => "a.isTemplate = '否' and a.coid = '" . self::$coid . "' and b.subjectId = '$subject[id]' and b.direction = '贷' and date_format(a.recordDate,'%Y-%m') < '$startMonth'" . $where));
        $jieInit['money'] = self::centToYuan($jieInit['money']);
        $daiInit['money'] = self::centToYuan($daiInit['money']);
        $jieMoney         = $jieInit['money'];
        $daiMoney         = $daiInit['money'];
        $jieMoney         += self::centToYuan((float)$subject['borrowMoney']);//借方
        $daiMoney         += self::centToYuan((float)$subject['loanMoney']);//贷方
        $jieInitNum       = $jieNum + $jieInit['num'];
        $daiInitNum       = $daiNum + $daiInit['num'];
        if ($subject['direction'] == '借') {
            $jieInit['num']   += $initNum;
            $jieInit['money'] += self::centToYuan((float)$subject['initMoney']);
        } else {
            $daiInit['num']   += $initNum;
            $daiInit['money'] += self::centToYuan((float)$subject['initMoney']);
        }

        if ($jieInit['money'] == $daiInit['money']) {
            $direction = '平';
            $balance   = $jieBalance = $daiBalance = 0;
        } elseif ($jieInit['money'] > $daiInit['money']) {
            $direction  = '借';
            $jieBalance = $jieInit['money'] - $daiInit['money'];
            $daiBalance = 0;
            $balance    = $jieBalance;
        } else {
            $direction  = '贷';
            $daiBalance = abs($jieInit['money'] - $daiInit['money']);
            $jieBalance = 0;
            $balance    = $daiBalance;
        }

        $result = [
            'jiePrice'     => self::division($jieMoney, $jieInitNum),
            'daiPrice'     => self::division($daiMoney, $daiInitNum),
            'jieInitNum'   => voucherEditClass::formatZero($jieInitNum),
            'daiInitNum'   => voucherEditClass::formatZero($daiInitNum),
            'balanceNum'   => voucherEditClass::formatZero($jieInit['num'] - $daiInit['num']),
            'balancePrice' => abs(self::division(abs($jieInit['money'] - $daiInit['money']), $jieInit['num'] - $daiInit['num'])),
            'jieMoney'     => round($jieMoney, 2),
            'daiMoney'     => round($daiMoney, 2),
            'jieBalance'   => round($jieBalance, 2),
            'daiBalance'   => round($daiBalance, 2),
            'direction'    => $direction,
            'balance'      => round($balance, 2)
        ];
        if (self::$isFormat) {
            $result = self::formatArrayNumber($result);
        }
        return $result;
    }


    /**
     * 期初余额
     * @param $subjectId
     * @param $startMonth
     * @return array
     */
    public function initMoneyDetail($subjectId, $startMonth): array
    {
        $subjectIds    = is_array($subjectId) ? $subjectId : [$subjectId];
        $where         = voucherClass::joinWhere();
        $jieTotalMoney = $daiTotalMoney = 0;
        $jieTotalNum   = $daiTotalNum = 0;
        $jieNum        = $daiNum = 0;
        $jieMoney      = $daiMoney = 0;
        foreach ($subjectIds as $id) {
            $subject = query('subject', "id = '$id'");
            //期初金额
            $initNum          = find(array('table' => 'subject_assist', "where" => "orderId = '$subject[id]'", 'sum' => "initNum"));
            $jieNum           = find(array('table' => 'subject_assist', "where" => "orderId = '$subject[id]'", 'sum' => "jieNum"));
            $daiNum           = find(array('table' => 'subject_assist', "where" => "orderId = '$subject[id]'", 'sum' => "daiNum"));
            $jieInit          = find(array("table" => "voucher as a join voucher_detail as b on a.id = b.orderId", 'field' => "ifnull(sum(b.money),0) as money,ifnull(sum(b.voucherNum),0) as num", "single" => "a.isTemplate = '否' and a.coid = '" . self::$coid . "' and b.subjectId = '$subject[id]' and b.direction = '借' and date_format(a.recordDate,'%Y-%m') < '$startMonth'" . $where));
            $daiInit          = find(array("table" => "voucher as a join voucher_detail as b on a.id = b.orderId", 'field' => "ifnull(sum(b.money),0) as money,ifnull(sum(b.voucherNum),0) as num", "single" => "a.isTemplate = '否' and a.coid = '" . self::$coid . "' and b.subjectId = '$subject[id]' and b.direction = '贷' and date_format(a.recordDate,'%Y-%m') < '$startMonth'" . $where));
            $jieInit['money'] = self::centToYuan($jieInit['money']);
            $daiInit['money'] = self::centToYuan($daiInit['money']);
            $jieTotalMoney    += $jieInit['money'];
            $jieTotalMoney    += self::centToYuan($subject['borrowMoney']);//借方
            $daiTotalMoney    += $daiInit['money'];
            $daiTotalMoney    += self::centToYuan($subject['loanMoney']);//贷方
            $jieTotalNum      += $jieNum + $jieInit['num'];
            $daiTotalNum      += $daiNum + $daiInit['num'];
            if ($subject['direction'] == '借') {
                $jieNum   += $jieInit['num'] + $initNum;
                $jieMoney += $jieInit['money'] + self::centToYuan($subject['initMoney']);
            } else {
                $daiNum   += $daiInit['num'] + $initNum;
                $daiMoney += $daiInit['money'] + self::centToYuan($subject['initMoney']);
            }
        }
        $result = [
            'jiePrice'     => self::division($jieTotalMoney, $jieTotalNum),
            'daiPrice'     => self::division($daiTotalMoney, $daiTotalNum),
            'jieInitNum'   => voucherEditClass::formatZero($jieTotalNum),
            'daiInitNum'   => voucherEditClass::formatZero($daiTotalNum),
            'balanceNum'   => voucherEditClass::formatZero($jieNum - $daiNum),
            'balancePrice' => abs(self::division(abs($jieMoney - $daiMoney), $jieNum - $daiNum)),
            'jieMoney'     => round($jieTotalMoney, 2),
            'daiMoney'     => round($daiTotalMoney, 2),
        ];
        if ($jieMoney > $daiMoney) {
            $result['jieBalance'] = round($jieMoney - $daiMoney, 2);
            $result['daiBalance'] = 0;
        } else {
            $result['daiBalance'] = round(abs($jieMoney - $daiMoney), 2);
            $result['jieBalance'] = 0;
        }
        if (self::$isFormat) {
            $result = self::formatArrayNumber($result);
        }
        return $result;
    }

    /**
     * 除法
     * @param $dividend
     * @param $divisor
     * @return float|int
     */
    public static function division($dividend, $divisor): float|int
    {
        if (empty($divisor) || $divisor == 0) {
            return 0;
        }
        return voucherEditClass::formatZero(voucherEditClass::formatPrice($dividend / $divisor), 2);
    }

    /**
     * 计算余额
     * @param $recordDate
     * @param $subjectId
     * @param $vourcherNo
     * @return array
     */
    public function balance($recordDate, $subjectId, $vourcherNo): array
    {
        return $this->balanceData($recordDate, $subjectId, $vourcherNo);
    }

    public function balanceData($recordDate, $subjectId, $vourcherNo)
    {
        $subject = query('subject', "id = '$subjectId'");
        $initNum = find(array('table' => 'subject_assist', "where" => "orderId = '$subject[id]'", 'sum' => "initNum"));
        //期初金额
        $initMoney = $subject['initMoney'];
        if ($vourcherNo == '累计') {
            $jieInit = find(array("table" => "voucher as a join voucher_detail as b on a.id = b.orderId", 'field' => "ifnull(sum(b.money),0) as money,ifnull(sum(b.voucherNum),0) as num", "single" => "a.isTemplate = '否' and a.coid = '" . self::$coid . "' and b.subjectId = '$subject[id]' and b.direction = '借' and a.recordDate <= '$recordDate'" . voucherClass::joinWhere()));
            $daiInit = find(array("table" => "voucher as a join voucher_detail as b on a.id = b.orderId", 'field' => "ifnull(sum(b.money),0) as money,ifnull(sum(b.voucherNum),0) as num", "single" => "a.isTemplate = '否' and a.coid = '" . self::$coid . "' and b.subjectId = '$subject[id]' and b.direction = '贷' and a.recordDate <= '$recordDate'" . voucherClass::joinWhere()));
        } else {
            $jieInit = find(array("table" => "voucher as a join voucher_detail as b on a.id = b.orderId", 'field' => "ifnull(sum(b.money),0) as money,ifnull(sum(b.voucherNum),0) as num", "single" => "a.isTemplate = '否' and a.coid = '" . self::$coid . "' and b.subjectId = '$subject[id]' and b.direction = '借' and if(a.recordDate='$recordDate',a.voucherNo<='$vourcherNo',a.recordDate <= '$recordDate')" . voucherClass::joinWhere()));
            $daiInit = find(array("table" => "voucher as a join voucher_detail as b on a.id = b.orderId", 'field' => "ifnull(sum(b.money),0) as money,ifnull(sum(b.voucherNum),0) as num", "single" => "a.isTemplate = '否' and a.coid = '" . self::$coid . "' and b.subjectId = '$subject[id]' and b.direction = '贷' and if(a.recordDate='$recordDate',a.voucherNo<='$vourcherNo',a.recordDate <= '$recordDate') " . voucherClass::joinWhere()));
        }

        if ($subject['direction'] == '借') {
            $jieInit['money'] += $initMoney;
            $balanceNum       = $jieInit['num'] + $initNum - $daiInit['num'];
        } else {
            $daiInit['money'] += $initMoney;
            $balanceNum       = $daiInit['num'] + $initNum - $jieInit['num'];
        }

        $jieInit['money'] = self::centToYuan($jieInit['money']);
        $daiInit['money'] = self::centToYuan($daiInit['money']);
        if ($jieInit['money'] == $daiInit['money']) {
            $direction  = '平';
            $jieBalance = 0;
            $daiBalance = 0;
        } elseif ($jieInit['money'] > $daiInit['money']) {
            $direction  = '借';
            $jieBalance = $jieInit['money'] - $daiInit['money'];
            $daiBalance = 0;
        } else {
            $direction  = '贷';
            $daiBalance = abs($jieInit['money'] - $daiInit['money']);
            $jieBalance = 0;
        }
        $result = ['direction' => $direction, 'balance' => round(abs($jieInit['money'] - $daiInit['money']), 2), 'balanceNum' => voucherEditClass::formatZero($balanceNum), 'balancePrice' => abs(self::division($jieInit['money'] - $daiInit['money'], $balanceNum)), 'jieBalance' => round($jieBalance, 2), 'daiBalance' => round($daiBalance, 2)];
        if (self::$isFormat) {
            $result = self::formatArrayNumber($result);
        }
        return $result;
    }

    public function balanceDetail($recordDate, $subjectId, $vourcherNo)
    {
        $subjectIds    = is_array($subjectId) ? $subjectId : [$subjectId];
        $jieTotalMoney = $daiTotalMoney = $jieTotalNum = $daiTotalNum = 0;
        foreach ($subjectIds as $id) {
            $subject = query('subject', "id = '$id'");
            $initNum = find(array('table' => 'subject_assist', "where" => "orderId = '$subject[id]'", 'sum' => "initNum"));
            //期初金额
            $initMoney = $subject['initMoney'];
            if ($vourcherNo == '累计') {
                $jieInit = find(array("table" => "voucher as a join voucher_detail as b on a.id = b.orderId", 'field' => "ifnull(sum(b.money),0) as money,ifnull(sum(b.voucherNum),0) as num", "single" => "a.isTemplate = '否' and a.coid = '" . self::$coid . "' and b.subjectId = '$subject[id]' and b.direction = '借' and a.recordDate <= '$recordDate'" . voucherClass::joinWhere()));
                $daiInit = find(array("table" => "voucher as a join voucher_detail as b on a.id = b.orderId", 'field' => "ifnull(sum(b.money),0) as money,ifnull(sum(b.voucherNum),0) as num", "single" => "a.isTemplate = '否' and a.coid = '" . self::$coid . "' and b.subjectId = '$subject[id]' and b.direction = '贷' and a.recordDate <= '$recordDate'" . voucherClass::joinWhere()));
            } else {
                $jieInit = find(array("table" => "voucher as a join voucher_detail as b on a.id = b.orderId", 'field' => "ifnull(sum(b.money),0) as money,ifnull(sum(b.voucherNum),0) as num", "single" => "a.isTemplate = '否' and a.coid = '" . self::$coid . "' and b.subjectId = '$subject[id]' and b.direction = '借' and if(a.recordDate='$recordDate',a.voucherNo<='$vourcherNo',a.recordDate <= '$recordDate')" . voucherClass::joinWhere()));
                $daiInit = find(array("table" => "voucher as a join voucher_detail as b on a.id = b.orderId", 'field' => "ifnull(sum(b.money),0) as money,ifnull(sum(b.voucherNum),0) as num", "single" => "a.isTemplate = '否' and a.coid = '" . self::$coid . "' and b.subjectId = '$subject[id]' and b.direction = '贷' and if(a.recordDate='$recordDate',a.voucherNo<='$vourcherNo',a.recordDate <= '$recordDate') " . voucherClass::joinWhere()));
            }

            if ($subject['direction'] == '借') {
                $jieInit['money'] += $initMoney;
                $jieTotalNum+= $jieInit['num'] + $initNum - $daiInit['num'];
            } else {
                $daiInit['money'] += $initMoney;
                $daiTotalNum+= $daiInit['num'] + $initNum - $jieInit['num'];
            }

            $jieTotalMoney += self::centToYuan($jieInit['money']);
            $daiTotalMoney += self::centToYuan($daiInit['money']);
        }

        if ($jieTotalMoney == $daiTotalMoney) {
            $direction  = '平';
            $jieBalance = 0;
            $daiBalance = 0;
        } elseif ($jieTotalMoney > $daiTotalMoney) {
            $direction  = '借';
            $jieBalance = $jieTotalMoney - $daiTotalMoney;
            $daiBalance = 0;
        } else {
            $direction  = '贷';
            $daiBalance = abs($jieTotalMoney - $daiTotalMoney);
            $jieBalance = 0;
        }
        $result = [
            'direction'    => $direction,
            'balance'      => round(abs($jieTotalMoney - $daiTotalMoney), 2),
            'balanceNum'   => voucherEditClass::formatZero(abs($jieTotalNum - $daiTotalNum)),
            'balancePrice' => abs(self::division($jieTotalMoney - $daiTotalMoney, abs($jieTotalNum - $daiTotalNum))),
            'jieBalance'   => round($jieBalance, 2),
            'daiBalance'   => round($daiBalance, 2)
        ];
        if (self::$isFormat) {
            $result = self::formatArrayNumber($result);
        }
        return $result;
    }

    /**
     * 录凭证页面实时计算
     * @param $recordDate
     * @param $subjectId
     * @param $vourcherNo
     * @param int $jieMoney
     * @param int $daiMoney
     * @param array $assetIds
     * @param string $voucherDetailId
     * @return array
     */
    public function balanceCul($recordDate, $subjectId, $vourcherNo, $jieMoney = 0, $daiMoney = 0, $assetIds = [], $voucherDetailId = ''): array
    {
        $subject = query('subject', "id = '$subjectId'");
        $where   = '';
        if (is_array($assetIds) && count($assetIds) > 0) {
            sort($assetIds);
            $idCollection = implode(',', $assetIds);
            $where        .= " and idCollection = '$idCollection'";
        }

        $initNum   = find(array('table' => 'subject_assist', "where" => "orderId = '$subject[id]'" . $where, 'sum' => "initNum"));
//        $initMoney = $subject['initMoney'];

        $voucherWhere = "a.isTemplate = '否' and a.coid = '" . self::$coid . "' and b.subjectId = '$subject[id]'";

        if ($vourcherNo == '累计') {
            $voucherWhere .= " and a.recordDate <= '$recordDate'" . voucherClass::joinWhere() . $where;
        } else {
            $voucherWhere .= " and if(a.recordDate='$recordDate',a.voucherNo<='$vourcherNo',a.recordDate <= '$recordDate')" . voucherClass::joinWhere();
        }

        //期初金额
        $jieInitAssist = find(array('table' => "subject_assist as a join subject as b on a.orderId = b.id", 'single' => "b.direction = '借' and a.orderId = '$subjectId'" . $where, 'field' => "ifnull(sum(a.initMoney),0) as money,ifnull(sum(a.initNum),0) as num"));
        $daiInitAssist = find(array('table' => "subject_assist as a join subject as b on a.orderId = b.id", 'single' => "b.direction = '贷' and a.orderId = '$subjectId'" . $where, 'field' => "ifnull(sum(a.initMoney),0) as money,ifnull(sum(a.initNum),0) as num"));

        $jieInit = find(array("table" => "voucher as a join voucher_detail as b on a.id = b.orderId", 'field' => "ifnull(sum(b.money),0) as money,ifnull(sum(b.voucherNum),0) as num", "single" => "$voucherWhere and b.direction = '借'"));
        $daiInit = find(array("table" => "voucher as a join voucher_detail as b on a.id = b.orderId", 'field' => "ifnull(sum(b.money),0) as money,ifnull(sum(b.voucherNum),0) as num", "single" => "$voucherWhere and b.direction = '贷'"));

        $decMoney      = 0;
        $voucherdetail = query('voucher_detail', "id = '$voucherDetailId'");
        if (!empty($voucherdetail['id'])) {
            $decMoney = $voucherdetail['direction'] == '借' ? ($subject['direction'] == '借' ? $voucherdetail['money'] : -$voucherdetail['money']) : ($subject['direction'] == '贷' ? $voucherdetail['money'] : -$voucherdetail['money']);
        }

        if ($subject['direction'] == '借') {
            $jieInit['money'] += self::yuanToCent($jieMoney) + self::yuanToCent($jieInitAssist['money']) - self::yuanToCent($daiMoney) - $decMoney;
            $balanceNum       = $jieInit['num'] + $initNum - $daiInit['num'];
        } else {
            $daiInit['money'] += self::yuanToCent($daiMoney) + self::yuanToCent($daiInitAssist['money']) - self::yuanToCent($jieMoney) - $decMoney;
            $balanceNum       = $daiInit['num'] + $initNum - $jieInit['num'];
        }


        $jieInit['money'] = self::centToYuan($jieInit['money']);
        $daiInit['money'] = self::centToYuan($daiInit['money']);

        if ($subject['direction'] == '借') {
            $balance = $jieInit['money'] - $daiInit['money'];
        } else {
            $balance = $daiInit['money'] - $jieInit['money'];
        }

        $direction  = '平';
        $jieBalance = 0;
        $daiBalance = 0;

        if ($jieInit['money'] != $daiInit['money']) {
            if ($jieInit['money'] > $daiInit['money']) {
                $direction  = '借';
                $jieBalance = $jieInit['money'] - $daiInit['money'];
            } else {
                $direction  = '贷';
                $daiBalance = abs($jieInit['money'] - $daiInit['money']);
            }
        }

        $result = [
            'direction'    => $direction,
            'balance'      => $balance,
            'balanceNum'   => voucherEditClass::formatZero($balanceNum),
            'balancePrice' => abs(self::division($jieInit['money'] - $daiInit['money'], $balanceNum)),
            'jieBalance'   => round($jieBalance, 2),
            'daiBalance'   => round($daiBalance, 2)
        ];

        if (self::$isFormat) {
            $result = self::formatArrayNumber($result);
        }

        return $result;
    }

    /**
     * 期末结转计算余额
     * @param $month
     * @param $subjectId
     * @return float
     */
    public function balanceOnlyMoney($month, $subjectId): float
    {
        $subject = query('subject', "id = '$subjectId'");
        //期初金额
        $initMoney = $subject['initMoney'];
        $jieInit   = find(array("table" => "voucher as a join voucher_detail as b on a.id = b.orderId", 'field' => "ifnull(sum(b.money),0) as money", "single" => "a.isTemplate = '否' and a.coid = '" . self::$coid . "' and b.subjectId = '$subject[id]' and b.direction = '借' and date_format(a.recordDate,'%Y-%m') <= '$month'" . voucherClass::joinWhere()));
        $daiInit   = find(array("table" => "voucher as a join voucher_detail as b on a.id = b.orderId", 'field' => "ifnull(sum(b.money),0) as money", "single" => "a.isTemplate = '否' and a.coid = '" . self::$coid . "' and b.subjectId = '$subject[id]' and b.direction = '贷' and date_format(a.recordDate,'%Y-%m') <= '$month'" . voucherClass::joinWhere()));
        if ($subject['direction'] == '借') {
            $jieInit['money'] += $initMoney;
        } else {
            $daiInit['money'] += $initMoney;
        }
        $jieInit['money'] = self::centToYuan($jieInit['money']);
        $daiInit['money'] = self::centToYuan($daiInit['money']);
        if ($jieInit['money'] > $daiInit['money']) {
            $balance = $jieInit['money'] - $daiInit['money'];
        } else {
            $balance = $daiInit['money'] - $jieInit['money'];
        }
        return round($balance, 2);
    }

    /**
     * 本期合计
     */
    public function monthBalance($month, $subjectId, $type = 'month'): array
    {
        $subject = query('subject', "id = '$subjectId'");
        if ($type == 'year') {
            $jieNum = find(array('table' => 'subject_assist', "where" => "orderId = '$subject[id]'", 'sum' => "jieNum"));
            $daiNum = find(array('table' => 'subject_assist', "where" => "orderId = '$subject[id]'", 'sum' => "daiNum"));
            //累计金额
            $jieMoney = $subject['borrowMoney'];
            $daiMoney = $subject['loanMoney'];
            $year     = date('Y', strtotime($month . '-01'));
            $where    = " and date_format(a.recordDate,'%Y') <= '$year' and date_format(a.recordDate,'%Y-%m') <= '$month'";
        } else {
            $jieNum   = $daiNum = 0;
            $jieMoney = $daiMoney = 0;
            $where    = " and date_format(a.recordDate,'%Y-%m') = '$month'";
        }
        $jieInit = find(array("table" => "voucher as a join voucher_detail as b on a.id = b.orderId", 'field' => "ifnull(sum(b.money),0) as money,ifnull(sum(b.voucherNum),0) as num", "single" => "a.isTemplate = '否' and a.coid = '" . self::$coid . "' and b.subjectId = '$subject[id]' and b.direction = '借'" . $where . voucherClass::joinWhere()));
        $daiInit = find(array("table" => "voucher as a join voucher_detail as b on a.id = b.orderId", 'field' => "ifnull(sum(b.money),0) as money,ifnull(sum(b.voucherNum),0) as num", "single" => "a.isTemplate = '否' and a.coid = '" . self::$coid . "' and b.subjectId = '$subject[id]' and b.direction = '贷'" . $where . voucherClass::joinWhere()));

        $jieInit['num']   = $jieInit['num'] + $jieNum;
        $daiInit['num']   = $daiInit['num'] + $daiNum;
        $jieInit['money'] = self::centToYuan($jieInit['money'] + $jieMoney);
        $daiInit['money'] = self::centToYuan($daiInit['money'] + $daiMoney);
        $result           = [
            'jiePrice' => self::division($jieInit['money'], $jieInit['num']),
            'daiPrice' => self::division($daiInit['money'], $daiInit['num']),
            'jieNum'   => voucherEditClass::formatZero($jieInit['num']),
            'daiNum'   => voucherEditClass::formatZero($daiInit['num']),
            'jieMoney' => round($jieInit['money'], 2),
            'daiMoney' => round($daiInit['money'], 2)
        ];
        if (self::$isFormat) {
            $result = self::formatArrayNumber($result);
        }
        return $result;
    }

    public function monthBalanceDetail($month, $subjectId, $type = 'month'): array
    {
        $subjectIds    = is_array($subjectId) ? $subjectId : [$subjectId];
        $jieTotalMoney = $daiTotalMoney = $jieTotalNum = $daiTotalNum = 0;
        foreach ($subjectIds as $id) {
            $subject = query('subject', "id = '$id'");
            if ($type == 'year') {
                $jieNum = find(array('table' => 'subject_assist', "where" => "orderId = '$subject[id]'", 'sum' => "jieNum"));
                $daiNum = find(array('table' => 'subject_assist', "where" => "orderId = '$subject[id]'", 'sum' => "daiNum"));
                //累计金额
                $jieMoney = $subject['borrowMoney'];
                $daiMoney = $subject['loanMoney'];
                $year     = date('Y', strtotime($month . '-01'));
                $where    = " and date_format(a.recordDate,'%Y') <= '$year' and date_format(a.recordDate,'%Y-%m') <= '$month'";
            } else {
                $jieNum   = $daiNum = 0;
                $jieMoney = $daiMoney = 0;
                $where    = " and date_format(a.recordDate,'%Y-%m') = '$month'";
            }
            $jieInit = find(array("table" => "voucher as a join voucher_detail as b on a.id = b.orderId", 'field' => "ifnull(sum(b.money),0) as money,ifnull(sum(b.voucherNum),0) as num", "single" => "a.isTemplate = '否' and a.coid = '" . self::$coid . "' and b.subjectId = '$subject[id]' and b.direction = '借'" . $where . voucherClass::joinWhere()));
            $daiInit = find(array("table" => "voucher as a join voucher_detail as b on a.id = b.orderId", 'field' => "ifnull(sum(b.money),0) as money,ifnull(sum(b.voucherNum),0) as num", "single" => "a.isTemplate = '否' and a.coid = '" . self::$coid . "' and b.subjectId = '$subject[id]' and b.direction = '贷'" . $where . voucherClass::joinWhere()));

            $jieTotalNum   += $jieInit['num'] + $jieNum;
            $daiTotalNum   += $daiInit['num'] + $daiNum;
            $jieTotalMoney += self::centToYuan($jieInit['money'] + $jieMoney);
            $daiTotalMoney += self::centToYuan($daiInit['money'] + $daiMoney);
        }

        $result = [
            'jiePrice' => self::division($jieTotalMoney, $jieTotalNum),
            'daiPrice' => self::division($daiTotalMoney, $daiTotalNum),
            'jieNum'   => voucherEditClass::formatZero($jieTotalNum),
            'daiNum'   => voucherEditClass::formatZero($daiTotalNum),
            'jieMoney' => round($jieTotalMoney, 2),
            'daiMoney' => round($daiTotalMoney, 2)
        ];
        if (self::$isFormat) {
            $result = self::formatArrayNumber($result);
        }
        return $result;
    }

    /**
     * 导出
     */
    public function exportData()
    {
        if (!$this->power(self::page, 'export')) {
            $_SESSION['warn'] = '你还没有导出的权限';
        } else {
            $tr     = [];
            $sql    = static::rGet(self::$stid . self::page . 'sql');
            $time   = static::rGet(self::$stid . self::page . 'time');
            $arr        = $time ? explode(' ~ ', $time) : [date('Y-m', strtotime(self::getMinDate())), date('Y-m', strtotime(self::getMaxDate()))];
            $arr[0] = trim($arr[0]);
            $arr[1] = trim(end($arr));
            $style  = static::rGet(self::$stid . self::page . 'tableStyle');
            if ($style == '金额式') {
                $title      = array("日期", "凭证字", "科目", '摘要', '借方', '贷方', '借方余额', '贷方余额');
                $subjectId  = static::rGet(self::$stid . self::page . 'subjectId');
                $time       = static::rGet(self::$stid . self::page . 'time');
                $arr        = $time ? explode(' ~ ', $time) : [date('Y-m'), date('Y-m')];
                $startMonth = trim($arr[0]);
                $initDate   = $startMonth . '-01';
                //获取查询结果
                $all     = sqlFind($sql);
                $subject = query('subject', "id = '$subjectId'");
                $result  = $this->initMoney($subjectId, $startMonth);
                $tr[]    = [$initDate, '', $subject['code'] . $subject['name'], '期初余额', $result['jieMoney'], $result['daiMoney'], $result['jieBalance'], $result['daiBalance']];
                foreach ($all as $index => $array) {
                    $voucher_word   = query('voucher_word', "id = '$array[voucherWordId]'");
                    $array['money'] = number_format(self::centToYuan($array['money']), 2);
                    if ($array['direction'] == '借') {
                        $jie = $array['money'];
                        $dai = '';
                    } else {
                        $jie = '';
                        $dai = $array['money'];
                    }
                    $result = $this->balance($array['recordDate'], $array['subjectId'], $array['voucherNo']);
                    $tr[]   = [$array['recordDate'], $voucher_word['word'] . '-' . $array['voucherNo'], $subject['code'] . $subject['name'], $array['summary'], $jie, $dai, $result['jieBalance'], $result['daiBalance']];

                    if ((isset($all[$index + 1]['subjectId']) && (date('Y-m', strtotime($all[$index + 1]['recordDate'])) != date('Y-m', strtotime($array['recordDate'])))) ||
                        !isset($all[$index + 1]['subjectId'])
                    ) {
                        $endMonthDate = date('Y-m', strtotime($array['recordDate']));
                        $result       = $this->monthBalance(date('Y-m', strtotime($array['recordDate'])), $array['subjectId']);
                        $balance      = $this->balance($array['recordDate'], $array['subjectId'], '累计');
                        $totalBalance = $this->monthBalance(date('Y-m', strtotime($array['recordDate'])), $subject['id'], 'year');
                        $tr[]         = [$endMonthDate, '', $subject['code'] . $subject['name'], '本期合计', $result['jieMoney'], $result['daiMoney'], $balance['jieBalance'], $balance['daiBalance']];

                        $tr[] = [$endMonthDate, '', $subject['code'] . $subject['name'], '本年累计', $totalBalance['jieMoney'], $totalBalance['daiMoney'], $balance['jieBalance'], $balance['daiBalance']];
                    }
                }
            } else {
                $title      = array("日期", "凭证字", "科目", '摘要', '借方数量', '借方单价', '借方金额', '贷方数量', '贷方单价', '贷方金额', '数量余额', '单价余额', '借方余额', '贷方余额');
                $subjectId  = static::rGet(self::$stid . self::page . 'subjectId');
                $time       = static::rGet(self::$stid . self::page . 'time');
                $arr        = $time ? explode(' ~ ', $time) : [date('Y-m'), date('Y-m')];
                $startMonth = trim($arr[0]);
                $initDate   = $startMonth . '-01';
                //获取查询结果
                $all     = sqlFind($sql);
                $subject = query('subject', "id = '$subjectId'");
                $result  = $this->initMoney($subjectId, $startMonth);
                $tr[]    = [$initDate, '', $subject['code'] . $subject['name'], '期初余额', $result['jieInitNum'], $result['jiePrice'], $result['jieMoney'], $result['daiInitNum'], $result['daiPrice'], $result['daiMoney'],
                    $result['balanceNum'], $result['balancePrice'], $result['jieBalance'], $result['daiBalance']];
                foreach ($all as $index => $array) {
                    $voucher_word        = query('voucher_word', "id = '$array[voucherWordId]'");
                    $array['money']      = number_format(self::centToYuan($array['money']), 2);
                    $array['voucherNum'] = voucherEditClass::formatZero($array['voucherNum']);
                    $balance             = $this->balance($array['recordDate'], $array['subjectId'], $array['voucherNo']);
                    if ($array['direction'] == '借') {
                        $subjectAttr                 = json_decode($array['subjectAttr'], true);
                        $subjectAttr['voucherPrice'] = $subjectAttr['voucherPrice'] ? floatval($subjectAttr['voucherPrice']) : '';
                        $tr[]                        = [$array['recordDate'], $voucher_word['word'] . $array['voucherNo'], $subject['code'] . $subject['name'], $array['summary'], $array['voucherNum'],
                            $subjectAttr['voucherPrice'], $array['money'], '', '', '', $balance['balanceNum'], $balance['balancePrice'], $balance['jieBalance'], $balance['daiBalance']];
                    } else {
                        $subjectAttr                 = json_decode($array['subjectAttr'], true);
                        $subjectAttr['voucherPrice'] = $subjectAttr['voucherPrice'] ? floatval($subjectAttr['voucherPrice']) : '';
                        $tr[]                        = [$array['recordDate'], $voucher_word['word'] . $array['voucherNo'], $subject['code'] . $subject['name'], $array['summary'], '', '', '', $array['voucherNum'],
                            $subjectAttr['voucherPrice'], $array['money'], $balance['balanceNum'], $balance['balancePrice'], $balance['jieBalance'], $balance['daiBalance']];
                    }


                    if ((isset($all[$index + 1]['subjectId']) && (date('Y-m', strtotime($all[$index + 1]['recordDate'])) != date('Y-m', strtotime($array['recordDate'])))) ||
                        !isset($all[$index + 1]['subjectId'])
                    ) {
                        $endMonthDate = date('Y-m', strtotime($array['recordDate']));
                        $result       = $this->monthBalance(date('Y-m', strtotime($array['recordDate'])), $subject['id']);
                        $balance      = $this->balance($array['recordDate'], $subject['id'], '累计');
                        $totalBalance = $this->monthBalance(date('Y-m', strtotime($array['recordDate'])), $subject['id'], 'year');

                        $tr[] = [$endMonthDate, '', $subject['code'] . $subject['name'], '本期合计', $result['jieNum'], $result['jiePrice'], $result['jieMoney'], $result['daiNum'],
                            $result['daiPrice'], $result['daiMoney'], $balance['balanceNum'], $balance['balancePrice'], $balance['jieBalance'], $balance['daiBalance']];
                        $tr[] = [$endMonthDate, '', $subject['code'] . $subject['name'], '本年累计', $totalBalance['jieNum'], $totalBalance['jiePrice'], $totalBalance['jieMoney'], $totalBalance['daiNum'],
                            $totalBalance['daiPrice'], $totalBalance['daiMoney'], $balance['balanceNum'], $balance['balancePrice'], $balance['jieBalance'], $balance['daiBalance']];
                    }
                }
            }
            $text = $this->control['name'] . "导出了" . self::title;
            $this->logText(["type" => self::page, "text" => $text]);
            $this->excelOut($title, $tr, self::title . ".xlsx");
        }
        header("Location:" . getenv("HTTP_REFERER"));
        exit(0);
    }
}
